﻿using System.Web;
using TemplateFoundation.Exceptions;
using TemplateFoundation.Reflection;

namespace TemplateFoundation.Handlers
{
    /// <summary>
    /// Provides access to HTML content embedded in the EPiServer Template Foundation assembly
    /// </summary>
    public class EmbeddedHtmlHandler : IHttpHandler
    {
        #region IHttpHandler Members

        private string _markup;
        private bool _fileFound = true;

        private const string REQUEST_URL_PREFIX = "/TemplateFoundation/";

        /// <summary>
        /// Creates a new embedded HTML handler
        /// </summary>
        public EmbeddedHtmlHandler()
        {
            var url = HttpContext.Current.Request.Url.AbsolutePath;

            if(!url.StartsWith(REQUEST_URL_PREFIX))
            {
                throw new TemplateFoundationException("Requests for HTML loader must be for a relative path starting with '" + REQUEST_URL_PREFIX + "'");
            }

            url = url.Substring(REQUEST_URL_PREFIX.Length).Replace('/','.');

            _markup = EmbeddedResourceLoader.LoadTextFile(string.Concat("Html.", url));

            // If HTML document contains full markup for testing, only markup within <body> tag should be returned
            // TODO Use RegEx to match <body> tag, even if it contains attributes
            if (string.IsNullOrEmpty(_markup))
            {
                _fileFound = false;
                return;
            }

            if(_markup.Contains("<body>"))
            {
                int startIndex = _markup.IndexOf("<body>")+6;
                int lastIndex = _markup.LastIndexOf("</body>");

                _markup = _markup.Substring(startIndex, lastIndex-startIndex).Trim();
            }
        }

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.
        /// </returns>
        public bool IsReusable
        {
            get { return false; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            if (_fileFound)
            {
                context.Response.Clear();
                context.Response.ContentType = "text/html";
                context.Response.StatusCode = 200;
                context.Response.Write(_markup);
                context.Response.End();
            }
            else
            {
                context.Response.Clear();
                context.Response.StatusCode = 404;
                context.Response.End();
            }
        }

        #endregion
    }
}
